package org.lalib.controller.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.lalib.acquire.IControllerService;
import org.lalib.entity.object.EFood;
import org.lalib.entity.object.EItem;
import org.lalib.entity.object.ETable;
import org.lalib.entity.object.EUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Scope("request")
@Service("cSearchService")
public class CSearchService implements IControllerService {

	private static final long serialVersionUID = 1L;

	@Autowired
	CUserService cUserService;

	@Autowired
	CFoodService cFoodService;

	@Autowired
	CTableService cTableService;

	public List<EItem> getTablesForGivenCriteria(String name, Long id) {
		List<EItem> itemList = new ArrayList<>();
		List<ETable> eTables = getTableListForNameOrId(name, id);
		if (eTables != null) {
			for (ETable eTable : eTables)
				itemList.add(eTable);
		}
		return itemList;
	}

	public List<EItem> getFoodsForGivenCriteria(String name, Long id) {
		List<EItem> itemList = new ArrayList<>();
		List<EFood> eFoods = getFoodListForNameOrId(name, id);
		if (eFoods != null) {
			for (EFood eFood : eFoods)
				itemList.add(eFood);
		}
		return itemList;
	}

	public List<EItem> getUsersForGivenCriteria(String name, Long id) {
		List<EItem> itemList = new ArrayList<>();
		List<EUser> eUsers = getUserListForNameOrId(name, id);
		if (eUsers != null) {
			for (EUser eUser : eUsers)
				itemList.add(eUser);
		}
		return itemList;
	}

	private List<EFood> getFoodListForNameOrId(String name, Long id) {
		if (name != null && !name.isEmpty())
			return cFoodService.getFoodListForGivenName(name);
		else if (id != null && id > 0)
			return Arrays.asList(cFoodService.getFoodById(id));
		return new ArrayList<>();
	}

	private List<EUser> getUserListForNameOrId(String name, Long id) {
		if (name != null && !name.isEmpty())
			return cUserService.getUserListForGivenName(name);
		else if (id != null && id > 0)
			return Arrays.asList(cUserService.getUserById(id));
		return new ArrayList<>();
	}

	private List<ETable> getTableListForNameOrId(String name, Long id) {
		if (name != null && !name.isEmpty())
			return cTableService.getTableListForGivenName(name);
		else if (id != null && id > 0)
			return Arrays.asList(cTableService.getTableById(id));
		return new ArrayList<>();
	}
}